//
//  HMSportCameraViewController.m
//  XRSport
//
//  Created by acer on 16/10/28.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "HMSportCameraViewController.h"
#import <AVFoundation/AVFoundation.h>

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

#define DURATIONTIME 1
@interface HMSportCameraViewController ()
//相机快门的动画的约束
@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *captureAnimationConstraints;
//预览视图
@property (weak, nonatomic) IBOutlet UIView *previousView;
//水印
@property (weak, nonatomic) IBOutlet UIImageView *waterPrintImageView;
//水印下方，运动距离
@property (weak, nonatomic) IBOutlet UILabel *sportDistanceLabel;
//照片保存成功提示语句
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
//左下角取消按钮
@property (weak, nonatomic) IBOutlet UIButton *cancelButton;
//右下角相机、分享按钮
@property (weak, nonatomic) IBOutlet UIButton *cameraReverseBtn;
//拍照按钮
@property (weak, nonatomic) IBOutlet UIButton *cameraCaptureBtn;

@end

@implementation HMSportCameraViewController
{
    AVCaptureDeviceInput *_captureInput;
    AVCaptureVideoPreviewLayer *_capturePreviewLayer;
    AVCaptureSession *_session;
    AVCaptureStillImageOutput *_imageOutput;
    //拍摄完成的图像
    UIImage *_capatureImage;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
}
-(void)setupCapturesession
{
    //input
    AVCaptureDevice *device = [self captureDevice];
    
    _captureInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:NULL];
    //输入输出添加到会话
    _session = [AVCaptureSession new];
    _imageOutput = [AVCaptureStillImageOutput new];
    if (![_session canAddInput:_captureInput]) {
        return;
    }
    if (![_session canAddOutput:_imageOutput]) {
        return;
    }
    [_session addInput:_captureInput];
    [_session addOutput:_imageOutput];
    //    设置预览涂层
    _capturePreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    CGRect rect = [UIScreen mainScreen].bounds;
    rect.size.height -= 130;
    _capturePreviewLayer.frame = rect;
    _capturePreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [_previousView.layer insertSublayer:_capturePreviewLayer atIndex:0];
    
    [self startCapture];
}
-(AVCaptureDevice *)captureDevice
{
    AVCaptureDevicePosition position = _captureInput.device.position;
    position = (position != AVCaptureDevicePositionBack) ? AVCaptureDevicePositionBack : AVCaptureDevicePositionFront;
    AVCaptureDevice *device;
    NSArray *array = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *obj in array) {
        if(obj.position == position)
        {
            device = obj;
            break;
        }
    }
    return device;
}
-(void)startCapture
{
    [_session startRunning];
}
-(void)stopCapture
{
    [_session stopRunning];
}
//拍照按钮点击
- (IBAction)roundCaptureClick:(UIButton *)sender {
    
    if (!_session.isRunning) {
        [self rotateButtonsAnimation];
        return;
    }
    
    [self cameraAnimationWith:YES];
    
    //    保存拍照图片
    [self saveCapturePicture];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(DURATIONTIME * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self cameraAnimationWith:NO];
    });
}
-(void)rotateButtonsAnimation
{
    BOOL emptyTitle = (_cameraCaptureBtn.currentTitle == nil);
    NSString *title = emptyTitle ? @"✓" : nil;
    [_cameraCaptureBtn setTitle:title forState:UIControlStateNormal];
    UIViewAnimationOptions options = emptyTitle ? UIViewAnimationOptionTransitionFlipFromRight : UIViewAnimationOptionTransitionFlipFromLeft;
    [UIView transitionWithView:_cameraCaptureBtn duration:DURATIONTIME options:options animations:nil   completion:^(BOOL finished) {
        
        if (title == nil) {
            [self startCapture];
        }
    }];
    
    NSString *imageName = emptyTitle ? @"ic_waterprint_share" : @"ic_waterprint_revolve";
    [_cameraReverseBtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [UIView transitionWithView:_cameraReverseBtn duration:DURATIONTIME options:options animations:nil completion:nil];
}
//相机翻转，分享按钮
- (IBAction)cameraReverse:(UIButton *)sender {
    
    if (!_session.isRunning) {
        //需要分享
        [self sharedPicture];
        return;
    }
    
    AVCaptureDevice *device = [self captureDevice];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:NULL];
    [self startCapture];
    [_session removeInput:_captureInput];
    if ([_session canAddInput:input]) {
        _captureInput = input;
    }
    [_session addInput:_captureInput];
    [self stopCapture];
}
//分享照片，第三方集成的代码
-(void)sharedPicture
{
    if (_capatureImage == nil) {
        return;
    }
    //1、创建分享参数
    NSArray* imageArray = @[_capatureImage];
    //（注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"分享内容"
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://mob.com"]
                                          title:@"分享标题"
                                           type:SSDKContentTypeAuto];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];
    }
    
}
-(void)cameraAnimationWith:(BOOL)close
{
    if (close) {
        [NSLayoutConstraint deactivateConstraints:_captureAnimationConstraints];
    } else {
        [NSLayoutConstraint activateConstraints:_captureAnimationConstraints];
        
        [self rotateButtonsAnimation];//???
    }
    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    }];
}
-(void)saveCapturePicture
{
    AVCaptureConnection *connection = _imageOutput.connections.firstObject;
    if (connection == nil) {
        return;
    }
    [_imageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == nil) {
            return ;
        }
        NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [UIImage imageWithData:data];
        
        CGRect rect = self.previousView.bounds;
        CGFloat offset = (self.view.frame.size.height - rect.size.height) * 0.5;
        UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
        [image drawInRect:CGRectInset(rect, 0, -offset)];
        
        [self.waterPrintImageView.image drawInRect:self.waterPrintImageView.frame];
        //        [self.sportDistanceLabel drawTextInRect:self.sportDistanceLabel.frame];
        [self.sportDistanceLabel.attributedText drawInRect:self.sportDistanceLabel.frame];
        
        UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        UIImageWriteToSavedPhotosAlbum(result, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    }];
}
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *meg = (error == nil) ? @"success" : @"faile";
    //    NSLog(@"%@",meg);
    self.tipLabel.text = meg;
    [self stopCapture];
    double duration = 0.25;
    [UIView animateWithDuration:duration delay:DURATIONTIME options:0 animations:^{
        self.tipLabel.alpha = 1.0;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:duration animations:^{
            
            self.tipLabel.alpha = 0;
        }];
    }];
    _capatureImage = image;
}
//退出按钮
- (IBAction)cancelCameraBtnClick:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
//隐藏状态栏
-(BOOL)prefersStatusBarHidden
{
    return YES;
}

@end
